#include "Stdafx.h"	

#include "EngineTests.h" 


BYTE RawDbGameBoard[GAMEBOARD_SIZE];

BYTE rowIndex[8] = { 5, 10, 14, 19, 23, 28, 32, 37 };

void ClearBoard(TGameBoard board)
{
	memset(board, 0, GAMEBOARD_SIZE * sizeof(BYTE));
	for(int i = 0; i < GAMEBOARD_SIZE; i++)
	{
		if(i == 5 || i == 10 || i == 14 || i == 19 || i == 23 || i == 28 || i == 32 || i == 37)
			i+=3;
		else
			board[i] = BORDER;
	}
}



void inline SetupFigure(uint32 bitMask, BYTE figure, TGameBoard board)
{

	while(bitMask)
	{
		int i = LSB(bitMask);
		bitMask ^= 1 << i;

		int col = i % 4;
		int row = i / 4;
		int index = rowIndex[row] + col;
		board[index] = figure;
	}
}


void RawDbSetupPosition(BitBoard* pos)
{
	ClearBoard(RawDbGameBoard);

	SetupFigure(pos->wm, WHITE_MAN, RawDbGameBoard);
	SetupFigure(pos->wk, WHITE_King, RawDbGameBoard);
	SetupFigure(pos->bm, BLACK_MAN, RawDbGameBoard);
	SetupFigure(pos->bk, BLACK_King, RawDbGameBoard);
}

void ConvertBoardFromBitBoard(BitBoard* pos, TGameBoard board)
{
	ClearBoard(board);

	SetupFigure(pos->wm, WHITE_MAN, board);
	SetupFigure(pos->wk, WHITE_King, board);
	SetupFigure(pos->bm, BLACK_MAN, board);
	SetupFigure(pos->bk, BLACK_King, board);
}

SMoveAnalysis* RawDbGenerateMoves(int color)
{
	SMoveAnalysis* pMoveAnalysis = new SMoveAnalysis();
	GenerateMoves(RawDbGameBoard, pMoveAnalysis, color == WHITE ? true : false);
	return pMoveAnalysis;
}

void RawDbDoMove(TSingleMove* pMove, bool bJump)
{
	ZOBRIST_KEY keyDummy = 0;
	DoMove(RawDbGameBoard, pMove, bJump, keyDummy);
}

void RawDbUndoMove(TSingleMove* pMove, bool bJump)
{
	ZOBRIST_KEY keyDummy = 0;
	UndoMove(RawDbGameBoard, pMove, bJump, keyDummy);
}



void inline GetFigureMask(uint32* bitMask, BYTE figure, TGameBoard board)
{
	uint32 mask = 0;


	for(int i = 5; i < GAMEBOARD_SIZE; i++)
	{
		if(board[i] == figure)
		{
			int row = 0;
			for(row = 0; row < 8 && rowIndex[row] <= i; row++);
			row--;
			int col = i - rowIndex[row];
			int index = row * 4 + col;
			mask |= 1 << index;
		}
	}

	*bitMask = mask;
}


void RawDbGetPosition(BitBoard* pos)
{
	GetFigureMask(&(pos->wm), WHITE_MAN, RawDbGameBoard);
	GetFigureMask(&(pos->wk), WHITE_King, RawDbGameBoard);
	GetFigureMask(&(pos->bm), BLACK_MAN, RawDbGameBoard);
	GetFigureMask(&(pos->bk), BLACK_King, RawDbGameBoard);
}

void ConvertBoardToBitboard(TGameBoard board, BitBoard* pos)
{
	GetFigureMask(&(pos->wm), WHITE_MAN, board);
	GetFigureMask(&(pos->wk), WHITE_King, board);
	GetFigureMask(&(pos->bm), BLACK_MAN, board);
	GetFigureMask(&(pos->bk), BLACK_King, board);
}
